//
//  JXHomeViewController.m
//  JXAddressApp
//
//  Created by huawei.zheng on 2018/10/27.
//  Copyright © 2018 zhhw_home. All rights reserved.
//

#import "JXHomeWebViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "QMUISearchBar.h"
#import "NSDictionary+JSON.h"
#import "EgovaNetworking.h"
#import "Masonry.h"
#import "JXPOIDetailView.h"
#import "BNCoreServices.h"
#import "NSDictionary+JSON.h"
#import "JXMeAddAddressViewController.h"
#import "QMUIImagePreviewViewController.h"
#import <QMUIKit/QMUICommonDefines.h>
#import <QMUIKit/UIColor+QMUI.h>
#import <QMUIKit/QMUIAlertController.h>
#import "JXAnnotation.h"
#import "JXBaseDefine.h"
#import <AFNetworking/AFNetworkReachabilityManager.h>
#import <Bugly/Bugly.h>
#import <WebKit/WebKit.h>

@interface JXHomeWebViewController ()
<
UISearchBarDelegate,
UITableViewDelegate,
UITableViewDataSource,
JXPOIDetailViewDelegate,
BNNaviRoutePlanDelegate,
BNNaviUIManagerDelegate,
QMUIImagePreviewViewDelegate
>

@property (nonatomic, strong) WKWebViewConfiguration    *webViewConfiguration;
@property (nonatomic, strong) WKWebView  *webView;
@property (nonatomic, strong) QMUISearchBar *searchBar;

@property (nonatomic, strong) UITableView  *resultTableView;
@property (nonatomic, strong) JXPOIDetailView   *detailView;

@property (nonatomic, strong) NSArray   *resultSets;
@property (nonatomic, strong) NSDictionary   *detailInfo;
@property (nonatomic, strong) NSArray   *images;

@property (nonatomic, strong) UIButton      *imageButton;
@property(nonatomic, strong) QMUIImagePreviewViewController *imagePreviewViewController;

@end

@implementation JXHomeWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    CGFloat navHeight = IS_NOTCHED_SCREEN?88:64;
    
    _webViewConfiguration = [[WKWebViewConfiguration alloc] init];
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, navHeight, SCREEN_WIDTH, SCREEN_HEIGHT-navHeight) configuration:self.webViewConfiguration];
    [self.view addSubview:_webView];
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.wegis.net/demo/view/mobile/map/index.html"]]];
    
    _searchBar = [[QMUISearchBar alloc] initWithFrame:CGRectMake(0,IS_NOTCHED_SCREEN?40:20, SCREEN_WIDTH, 44)];
    _searchBar.delegate = self;
    _searchBar.backgroundColor = [UIColor whiteColor];
    if(@available(iOS 11.0, *)) {
        [[_searchBar.heightAnchor constraintEqualToConstant:44] setActive:YES];
    }
    
    [self.view addSubview:_searchBar];
    [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].title = @"取消";
    
    for (UIView *subview in _searchBar.subviews) {
        for(UIView* grandSonView in subview.subviews){
            if ([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
                grandSonView.alpha = 0.0f;
            }else if([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarTextField")] ){
                NSLog(@"Keep textfiedld bkg color");
            }else{
                grandSonView.alpha = 0.0f;
            }
        }//for cacheViews
    }//subviews
    
    _resultTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _resultTableView.tableFooterView = [UIView new];
    _resultTableView.delegate = self;
    _resultTableView.dataSource = self;
    _resultTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _resultTableView.hidden = YES;
    [self.view addSubview:_resultTableView];
    
    if (@available(iOS 11.0, *)) {
        _resultTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    CGFloat height = SCREEN_HEIGHT- (IS_NOTCHED_SCREEN?88:64) - (IS_NOTCHED_SCREEN?88:48);
    _resultTableView.frame = CGRectMake(0, (IS_NOTCHED_SCREEN?88:64), SCREEN_WIDTH, height);
    
    JXPOIDetailView *detailView = [[JXPOIDetailView alloc] init];
    detailView.hidden = YES;
    detailView.delegate = self;
    [self.view addSubview:detailView];
    
    CGFloat tabbarHeight = IS_NOTCHED_SCREEN?83:48;
    
    CGFloat viewY = SCREEN_HEIGHT-tabbarHeight;
    detailView.frame = CGRectMake(0, viewY-70, SCREEN_WIDTH, 230);
    self.detailView = detailView;
    
    if ([AFNetworkReachabilityManager sharedManager].isReachable == NO) {
        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{@"msg":@"首页进入网络异常"}];
        [Bugly reportError:error];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];

//    if (_mapView.UserTrackMode == TUserTrackingModeFollow) {
//        [_mapView StartGetPosition];
//    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)mapViewWillStartLocatingUser:(TMapView *)mapView
{
    NSLog(@"开始定位");
}

- (void)mapViewDidStopLocatingUser:(TMapView *)mapView
{
    NSLog(@"停止定位");
}

- (void)mapView:(TMapView *)mapView didChangeUserTrackingMode:(TUserTrackingMode)mode animated:(BOOL)animated
{
}

- (void)mapView:(TMapView *)mapView didUpdateUserLocation:(TUserLocation *)userLocation
{
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self search:searchText];
}

- (void)search:(NSString*)keyword
{
    NSDictionary *params = @{@"q":keyword?:@"",
                             @"type":@(-1),
                             @"limit":@(10)
                             };

    NSString *url = @"http://www.wegis.net/demo/home/baseinfo/getplacebyname";
    [EgovaNetworking postWithUrl:url cache:NO params:params completed:^(NSInteger code, id data, NSString *msg) {
        self.resultSets = data[@"features"];
        
        [self.resultTableView reloadData];
    }];
}

- (void)searchDetail:(NSString*)code name:(NSString*)name
{
    NSDictionary *params = @{@"code":code,
                             @"stype": @(1),
                             @"searchname": name
                             };
    
    NSString *url = @"http://www.wegis.net/demo/home/baseinfo/getplacebycode";
    [EgovaNetworking getWithUrl:url cache:NO params:params completed:^(NSInteger code, id data, NSString *msg) {
        if (code==0 && data) {
            self.detailInfo = data;
            
            [self showDetailView];
        }
    }];
    
    [self searchImages:code];
}

- (void)searchImages:(NSString*)code
{
    NSDictionary *params = @{@"code":code,
                             @"type": @(5)
                             };
    
    NSString *url = @"http://www.wegis.net/demo/home/baseinfo/getplacemedia";
    [EgovaNetworking getWithUrl:url cache:NO params:params completed:^(NSInteger code, id data, NSString *msg) {
        if (code==0 && data) {
            self.images = data[@"media"];
            [self.detailView updateImages:self.images];
        }
    }];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    _resultTableView.hidden = NO;
    _searchBar.showsCancelButton = YES;
    
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    _resultTableView.hidden = YES;
    _searchBar.showsCancelButton = NO;
    
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    
    _resultTableView.hidden = YES;
}

- (void)showDetailView
{
    self.detailView.hidden = NO;
    
    [self.detailView updateInfo:_detailInfo];
    [self.detailView updateImages:self.images];
}

#pragma mark - UITalbeView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _resultSets.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainSearchCell"];
    NSDictionary *item = _resultSets[indexPath.row];
    
    cell.textLabel.text = item[@"name"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = [_resultSets objectAtIndex:indexPath.row];
    
    [self searchDetail:item[@"code"] name:item[@"name"]];
    
    [self.searchBar resignFirstResponder];
    
    [self toPosition:item];
     
    [self.searchBar setText:item[@"name"]];
}

- (void)toPosition:(NSDictionary*)item
{
    NSString *geometryJson = item[@"geometry"];
    NSDictionary *geometry = [NSDictionary JSONObject:geometryJson];
    NSArray *coordinates = geometry[@"coordinates"];
    CGFloat x = 0;
    CGFloat y = 0;
    if ([[coordinates firstObject] isKindOfClass:[NSArray class]]) {
        NSArray *point = [coordinates firstObject];
        
        x = [point[0] floatValue];
        y = [point[1] floatValue];
    }
    else {
        x = [coordinates[0] floatValue];
        y = [coordinates[1] floatValue];
    }
    
//    [_mapView setMapScale:1 animated:NO];
//    [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(y, x) animated:YES];
//
}

- (void)editorAction:(NSDictionary *)item
{
    JXMeAddAddressViewController *vc = [JXMeAddAddressViewController new];
    vc.item = item[@"place"];
    
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)imageClick:(NSInteger)index view:(UIButton*)view
{
    self.imageButton = view;
                        
    [self showImage:index view:view];
}

- (void)showImage:(NSInteger)index view:(UIButton*)view
{
    if (!self.imagePreviewViewController) {
        self.imagePreviewViewController = [[QMUIImagePreviewViewController alloc] init];
        self.imagePreviewViewController.imagePreviewView.delegate = self;
        self.imagePreviewViewController.imagePreviewView.currentImageIndex = 0;// 默认查看的图片的 index
        
        // QMUIImagePreviewViewController 对于以 window 的方式展示的情况，默认会开启手势拖拽退出预览功能。
        // 如果使用了手势拖拽，并且退出预览时需要飞到某个 rect，则需要实现这个 block，在里面自己去 exit，如果不实现这个 block，退出动画会使用 fadeOut 那种
        __weak __typeof(self)weakSelf = self;
        self.imagePreviewViewController.customGestureExitBlock = ^(QMUIImagePreviewViewController *aImagePreviewViewController, QMUIZoomImageView *currentZoomImageView) {
            
            weakSelf.imageButton = nil;
            [aImagePreviewViewController exitPreviewToRectInScreenCoordinate:[view convertRect:view.imageView.frame toView:nil]];
        };
    }
    
    [self.imagePreviewViewController startPreviewFromRectInScreenCoordinate:[view convertRect:view.imageView.frame toView:nil] cornerRadius:view.layer.cornerRadius];
}

#pragma mark - <QMUIImagePreviewViewDelegate>

- (NSUInteger)numberOfImagesInImagePreviewView:(QMUIImagePreviewView *)imagePreviewView {
    return 1;
}

- (void)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView renderZoomImageView:(QMUIZoomImageView *)zoomImageView atIndex:(NSUInteger)index
{
    zoomImageView.image = self.imageButton.imageView.image;
}

- (QMUIImagePreviewMediaType)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView assetTypeAtIndex:(NSUInteger)index
{
    return QMUIImagePreviewMediaTypeImage;
}

- (void)locationTo
{
    NSString js = [[NSString alloc] initWithFormat:@"locationPic(%f, %f)", 0, 0];
    [_webView evaluateJavaScript:@"" completionHandler:nil];
}

#pragma mark - <QMUIZoomImageViewDelegate>

- (void)singleTouchInZoomingImageView:(QMUIZoomImageView *)zoomImageView location:(CGPoint)location
{
    self.imagePreviewViewController.customGestureExitBlock(self.imagePreviewViewController, zoomImageView);
}

- (void)startNavigation:(NSDictionary*)item
{
    NSString *geometryJson = item[@"place"][@"geometry"];
    NSDictionary *geometry = [NSDictionary JSONObject:geometryJson];
    NSArray *coordinates = geometry[@"coordinates"];
    CGFloat x = 0;
    CGFloat y = 0;
    if ([[coordinates firstObject] isKindOfClass:[NSArray class]]) {
        NSArray *point = [coordinates firstObject];
        
        x = [point[0] floatValue];
        y = [point[1] floatValue];
    }
    else {
        x = [coordinates[0] floatValue];
        y = [coordinates[1] floatValue];
    }
    
    [self startNavi:x y:y];
}


//发起导航
- (void)startNavi:(CGFloat)x y:(CGFloat)y
{
    //节点数组
    NSMutableArray *nodesArray = [[NSMutableArray alloc]    initWithCapacity:2];
    
    //起点
    BNRoutePlanNode *startNode = [[BNRoutePlanNode alloc] init];
    startNode.pos = [[BNPosition alloc] init];
//    startNode.pos.x = self.mapView.userLocation.location.coordinate.longitude;
//    startNode.pos.y = self.mapView.userLocation.location.coordinate.latitude;
    startNode.pos.eType = BNCoordinate_OriginalGPS;
    [nodesArray addObject:startNode];
    
    //终点
    BNRoutePlanNode *endNode = [[BNRoutePlanNode alloc] init];
    endNode.pos = [[BNPosition alloc] init];
    endNode.pos.x = x;
    endNode.pos.y = y;
    endNode.pos.eType = BNCoordinate_OriginalGPS;
    [nodesArray addObject:endNode];
    //发起路径规划
    [BNCoreServices_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Recommend naviNodes:nodesArray time:nil delegete:self userInfo:nil];
}

//算路成功回调
-(void)routePlanDidFinished:(NSDictionary *)userInfo
{
    NSLog(@"算路成功");
    
    //路径规划成功，开始导航
    [BNCoreServices_UI showPage:BNaviUI_NormalNavi delegate:self extParams:nil];
}


@end
